(function ($) {
    // general settings
    $.fn.modal.defaults.spinner = $.fn.modalmanager.defaults.spinner =
        '<div class="loading-spinner" style="width: 200px; margin-left: -100px;">' +
        '<div class="progress progress-striped active">' +
        '<div class="progress-bar" style="width: 100%;"></div>' +
        '</div>' +
        '</div>';

    $.fn.modalmanager.defaults.resize = true;

    top.dialogs = [];

    /**
     * build the dialog
     */
    function buildDialog(target) {
        var opts = $.data(target, 'modalDialog').options;
        var $modal = top.$("<div>", {
            id: "modal" + new Date().getTime(),
            class: "modal",
            tabindex: -1,
        });
        //}).appendTo(top.$("body"));
        $modal.target = target;
        $modal.params = opts.params;
        $modal.callBack = opts.callBack;
        $modal.closing = opts.closing;
        top.dialogs.unshift($modal);
        $modal.on('shown.bs.modal', function (e) {
            setActualSize(this, opts);
            if ($modal.success) {
                top.App.easyuiParse($modal[0]);
                $modal.success();
            }

            //解决弹窗和时间控件之间隐藏事件冲突
            $('.date-picker').on('hide', function(event) {
                event.stopPropagation();
            });
            // console.log($(this).find(".modal-header").height());
            // $(this).css({"minWidth": opts.width, "maxHeight": opts.height});
        });

        var boo = false;
        $modal.on('hide.bs.modal', function (e) {
            if ($modal.closing) {
                var result = $modal.closing();
                if(result == false){
                    return false;
                }
            }
            $(this).parent().prev().remove();
            $(this).parent().remove();
            top.sweetAlert.close();
        });
        top.$('body').modalmanager('loading');
		if(opts.container){
			var container = opts.container.clone(true);
			container.find("script").attr("type","text/javascript");
			container.find("style").attr("type","text/css");
			$modal.append(container.html());
			$modal.modal({
				backdrop:'static',
				keyboard: opts.keyboard,
				width: opts.width,
				height: opts.height,
				attentionAnimation: ""
			}).css({
				'margin-top': function () {
					var modalHeight = $modal.outerHeight();
					return -(modalHeight / 2);
				},
				'margin-left': function () {
					var modalWidth = $modal.outerWidth();
					return -(modalWidth / 2);
				}
			});
		} else {
			$modal.load(opts.url, '', function (response,status,xhr) {
				if(status === "success") {
					$modal.modal({
						backdrop:'static',
						keyboard: opts.keyboard,
						width: opts.width,
						height: opts.height,
						attentionAnimation: ""
					}).css({
						'margin-top': function () {
							var modalHeight = $modal.outerHeight();
							return -(modalHeight / 2);
						},
						'margin-left': function () {
							var modalWidth = $modal.outerWidth();
							return -(modalWidth / 2);
						}
					});
				} else {
					top.$('body').modalmanager('removeLoading');
					$modal.remove();
					if (401 == xhr.status || 403 == xhr.status) {
					    window.location.href = "/error/" + xhr.status;
					} else {
						$.messager.alert("错误", "请联系管理员！", "warning");
					}
				}
			});
		}
    }

    function setActualSize(e, opts) {
        $(e).width(opts.width);
        $(e).find(".modal-header").css("padding", "5px 10px");
        $(e).find(".modal-footer").css("padding", "5px 10px");
        $(e).find(".modal-header .close").css("cssText", "margin-top:8px!important");
        var header = $(e).find(".modal-header").outerHeight(true);
        var footer = $(e).find(".modal-footer").outerHeight(true);
        $(e).find(".modal-body").height(opts.height - header - footer);
        $(e).find(".modal-body").css("overflow", "hidden");
        $(e).find(".modal-body").css("overflow-y", "auto");
		
		//设置z-index层级
		var zIndex = 0;
		$(".modal-scrollable").each(function(){
			var $zIndex = parseInt($(this).css("z-index"));
			if(!($zIndex === $(e).parent().css("z-index")) && $zIndex > zIndex) zIndex = $zIndex;
		});
		if(!zIndex) zIndex = 100;
		if(zIndex > 100 + $(".modal-scrollable").length * 3) zIndex = 100 + $(".modal-scrollable").length * 3;
		$(e).parent().prev().css("z-index", zIndex + 1);
		$(e).parent().css("z-index", zIndex + 2);
		
    }

    function getWindowSize() {
        var winWidth;
        var winHeight;
        // 获取窗口宽度
        if (window.innerWidth)
            winWidth = window.innerWidth;
        else if ((document.body) && (document.body.clientWidth))
            winWidth = document.body.clientWidth;
        // 获取窗口高度
        if (window.innerHeight)
            winHeight = window.innerHeight;
        else if ((document.body) && (document.body.clientHeight))
            winHeight = document.body.clientHeight;
        // 通过深入 Document 内部对 body 进行检测，获取窗口大小
        if (document.documentElement && document.documentElement.clientHeight && document.documentElement.clientWidth) {
            winHeight = document.documentElement.clientHeight;
            winWidth = document.documentElement.clientWidth;
        }
        return {"winWidth": winWidth, "winHeight": winHeight};
    }

    $.fn.modalDialog = function (options, param) {
        if (typeof options == 'string') {
            var method = $.fn.modalDialog.methods[options];
            if (method) {
                return method(this, param);
            }
        }

        options = options || {};
        return this.each(function () {
            var state = $.data(this, 'modalDialog');
            if (state) {
                $.extend(state.options, options);
            } else {
                $.data(this, 'modalDialog', {
                    options: $.extend({}, $.fn.modalDialog.defaults, $.fn.modalDialog.parseOptions(this), options)
                });
            }
            $(this).on("click", function () {
                buildDialog(this);
            });
            // $(this).focus(function () {
            //     // $(this).click();
            //     buildDialog(this);
            // });
        });
    };

    $.fn.modalDialog.methods = {
        options: function (jq) {
            return $.data(jq[0], 'modalDialog').options;
        },
        dialog: function (jq) {
            return jq.window('window');
        },
        setOptions: function (jq, options) {
            var state = $.data(jq[0], 'modalDialog');
            $.extend(state.options, options);
        }
    };

    $.fn.modalDialog.parseOptions = function (target) {
        var t = $(target);
        return {};
    };

    $.fn.modalDialog.defaults = $.extend({}, {
        title: '新的窗口',
        className: "modalDialog",
        params: {},
        onEscape: function () {
            dialogs.shift();
        },
        keyboard: false,//esc按键 false代表不关闭弹窗
        width: getWindowSize().winWidth * 0.8,
        height: getWindowSize().winHeight * 0.8
    });
})(jQuery);